<template>
  <div class="menu-permission-container">
    <el-card class="menu-permission-card">
      <div slot="header" class="clearfix">
        <span>菜单权限分配</span>
      </div>
      
      <el-form :model="permissionForm" label-width="120px">
        <el-form-item label="选择用户：">
          <el-select v-model="permissionForm.userId" placeholder="请选择用户" @change="loadUserPermissions(permissionForm.userId)">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username + ' (' + user.role + ')'"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="分配菜单权限：">
          <el-tree
            ref="menuTree"
            :data="menuData"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedMenus"
            :props="defaultProps"
            :expand-on-click-node="false">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
            </span>
          </el-tree>
          <!-- 调试信息：显示菜单数据 -->
          <div v-if="menuData.length === 0">暂无菜单数据</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="savePermissions" :loading="saving">保存权限</el-button>
          <el-button @click="resetPermissions">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'element-ui/lib/theme-chalk/index.css';
import { RolePermissionUtil } from '@/utils/rolePermission';
import { Card, Tree, Form, FormItem, Select, Option, Button } from 'element-ui';
import axios from 'axios';

export default {
  name: 'MenuPermission',
  components: {
    ElCard: Card,
    ElTree: Tree,
    ElForm: Form,
    ElFormItem: FormItem,
    ElSelect: Select,
    ElOption: Option,
    ElButton: Button
  },
  data() {
    return {
      permissionForm: {
        userId: ''
      },
      userList: [],
      menuData: [
        {
          id: 1,
          label: '业务统计',
          path: '/admin/business-stats',
          permission: 'business:stats:view'
        },
        {
          id: 2,
          label: '项目总览',
          path: '/admin/project-overview',
          permission: 'project:overview:view'
        },
        {
          id: 3,
          label: '标注员管理',
          path: '/admin/labeler-management',
          permission: 'labeler:management:view'
        },
        {
          id: 4,
          label: '标注员产值记录',
          path: '/admin/labeler-daily-output',
          permission: 'labeler:daily:output:view'
        },
        {
          id: 5,
          label: '标注员拉框数',
          path: '/admin/labeler-box-count',
          permission: 'labeler:box:count:view'
        },
        {
          id: 6,
          label: '质检统计',
          path: '/admin/qc-statistics',
          permission: 'qc:statistics:view'
        },
        {
          id: 7,
          label: '优秀标注员',
          path: '/admin/excellent-labeler',
          permission: 'excellent:labeler:view'
        },
        {
          id: 8,
          label: '优秀项目经理',
          path: '/admin/excellent-manager',
          permission: 'excellent:manager:view'
        },
        {
          id: 9,
          label: '数据项目看板',
          path: '/admin/data-project',
          permission: 'data:project:view'
        },
        {
          id: 10,
          label: '大屏配置',
          path: '/admin/screen-config',
          permission: 'screen:config:view'
        },
        {
          id: 11,
          label: '供应商采集管理',
          path: '/admin/supplier-collection',
          permission: 'supplier:collection:view'
        },
        {
          id: 12,
          label: '菜单权限分配',
          path: '/admin/menu-permission',
          permission: 'menu:permission:view'
        }
      ],
      checkedMenus: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      saving: false
    };
  },
  created() {
    // 检查当前用户是否为管理员
    if (!RolePermissionUtil.isAdmin()) {
      this.$message.error('只有管理员才能访问此页面');
      this.$router.push('/admin');
      return;
    }
    
    this.loadUserList();
    

  },
  methods: {
    // 加载用户列表
    loadUserList() {
      // 调用后端接口获取用户列表
      axios.get('/admin/users')
        .then(response => {
          console.log("权限菜单返回值:",response);
          // 修复响应数据结构访问（经过拦截器处理后，直接访问code）
          if (response.data.code === 200) {
            console.log("jinru:");
            this.userList = response.data.data;
            console.log("结果集:",this.userList)
          }else if (response.code === 200) {
             this.userList = response.data;
            console.log("结果集22:",this.userList)
          } else {
            this.$message.error(response.message || '获取用户列表失败222');
          }
        })
        .catch(error => {
          console.log('获取用户列表失败:', error);
          this.$message.error('获取用户列表失败: ' + error.message);
        });
    },
    
    // 加载用户权限
    loadUserPermissions(userId) {
      // 调用后端接口获取用户的菜单权限
      axios.get(`/admin/menus/user/${userId}`)
        .then(response => {
          console.log("用户获取-----",response)
          // 修复响应数据结构访问（经过拦截器处理后，直接访问code）
          if (response.data.code === 200) {
            this.checkedMenus = response.data.data;
            this.$nextTick(() => {
              this.$refs.menuTree.setCheckedKeys(this.checkedMenus);
            });
          }else if (response.code === 200) {
             this.checkedMenus = response.data;
            this.$nextTick(() => {
              this.$refs.menuTree.setCheckedKeys(this.checkedMenus);
            });
          } else {
            this.$message.error(response.data.message || '获取用户权限失败');
          }
        })
        .catch(error => {
          this.$message.error('获取用户权限失败: ' + error.message);
        });
    },
    
    // 保存权限
    savePermissions() {
      if (!this.permissionForm.userId) {
        this.$message.warning('请选择用户');
        return;
      }
      
      // 修复 Element UI Tree 组件方法调用问题
      this.$nextTick(() => {
        const checkedNodes = this.$refs.menuTree.getCheckedNodes();
        const checkedKeys = this.$refs.menuTree.getCheckedKeys();
        
        // 调用后端接口保存权限
        axios.post('/admin/user-menu', {
          userId: this.permissionForm.userId,
          menuIds: checkedKeys
        })
          .then(response => {
            // 修复响应数据结构访问（经过拦截器处理后，直接访问code）
            console.log("保存成功====",response)
            if (response.code === 200) {
              this.$message.success('权限保存成功');
            } else if (response.data.code === 200) {
                this.$message.success('权限保存成功');
            } else {
              this.$message.error(response.message || '权限保存失败');
            }
          })
          .catch(error => {
            this.$message.error('权限保存失败222: ' + error.message);
          });
      });
    },
    
    // 重置权限
    resetPermissions() {
      this.$refs.menuTree.setCheckedKeys([]);
      this.checkedMenus = [];
      this.permissionForm.userId = '';
    },
  }
};
</script>

<style lang="scss" scoped>
.menu-permission-container {
  padding: 20px;
  
  .menu-permission-card {
    margin-bottom: 20px;
  }
  
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>